﻿/*----------------------------------------------------------------
    // Copyright (C) 2009 江苏华招网
    // 版权所有。 
    // 作者：袁世明 
    //
    // 文件名：PurchasePriceUpdate.cs
    // 文件功能描述：设置采购目录的实际采购价
    // 创建标识：袁世明2013-01-30
    //
    // 修改标识：
    // 修改描述：
    //
    // 修改标识：
    // 修改描述：
    //
    // 审核人：
// 审核时间：
// 审核说明：
 //----------------------------------------------------------------*/
using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HZ.DrugTrade.BLLFactory;
using HZ.DrugTrade.IBLL;
using HZ.DrugTrade.Model;
using System.Collections;
using System.Data;

namespace HZ.DrugTrade.Web.Hospitals.Procurement
{
    public partial class PurchasePriceUpdate : BasePage
    {
        protected string strPriceProvenance = "";
        protected string GoodsId = string.Empty;
        public PurchasePriceUpdate()
        {
            this.ModuleNo = "";
        }
        public static string ProjectID = string.Empty;
        IBLL_Distribution id = Factory.BLL_Distribution();
        IBLL_HospitalProcureCatalog hpcCtrl = Factory.BLL_HospitalProcureCatalog();
        IBLL_ProcurementBasic pbCtrl = Factory.BLL_ProcurementBasic();
        public bool BoolSelect = false;
        protected void Page_Load(object sender, EventArgs e)
        {


            string procureCatalogId = Request.QueryString["procureCatalogId"];
            lblgoodsid.Text = procureCatalogId;
            GoodsId = procureCatalogId;
            //by ligang 2009-6-15
            HZ.DrugTrade.Model.View.ProcureCatalog procureCatalog = pbCtrl.GetProcureCatalogByID(procureCatalogId);
            if (procureCatalog != null)
            {
                //非采购产品单独设置配送企业 0 竞价议价，1重点监控，2，自行采购，3临时采购
                if ((procureCatalog.SortSource ?? 3) >= 3)
                {
                    Server.Transfer("PurchaseCompanyUpdate_UnBid.aspx", true);
                }
            }
            else
            {
                PageError("采购产品不存在！", this.ReturnUrl);
            }

            if (!IsPostBack)
            {
                BindAllCompanyList();
                BindOperationRecords();
                Bind();
            }
        }

        /// <summary>
        /// 绑定所有可选的配送企业
        /// </summary>
        private void BindAllCompanyList()
        {
            string procureCatalogId = Request.QueryString["procureCatalogId"];
            string hospitalId = CurrentAccount.GetUser().Org.OrgID;
            int tmpCount;
            HZ.DrugTrade.Model.View.HospitalProcureCatalog hospitalProcureCatalog = hpcCtrl.GetHospitalProcureCatalog(
                new HZ.DrugTrade.Model.Query.HospitalProcureCatalog() { ProcureCatalogID = procureCatalogId, HospitalID = hospitalId }, 1, 0, out tmpCount)[0];
            if (hospitalProcureCatalog != null)
            {
                this.lblGoodsName.Text = hospitalProcureCatalog.GoodsName;
                this.lblMaterial.Text = hospitalProcureCatalog.Material;
                this.lblGg.Text = hospitalProcureCatalog.Outlookc;
                this.lblCompanyName_SC.Text = hospitalProcureCatalog.CompanyName_SC;
                this.lblCompanyName_ZB.Text = hospitalProcureCatalog.CompanyName_TB;
                if (hospitalProcureCatalog.ProjectID == "0002")
                {
                    if (!string.IsNullOrEmpty(hospitalProcureCatalog.Bidprice.ToString()))
                    {
                        this.lblBidPrice2014.Text = (hospitalProcureCatalog.Bidprice.Value == 0) ? "NA" : HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.Bidprice);
                    }
                    this.lblProcureprice2014.Text = (hospitalProcureCatalog.ProcurePrice.Value == 0) ? "NA" : HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.ProcurePrice);
                    hc2012.Visible = false;
                    hc2014.Visible = true;
                    hc20142.Visible = true;
                }
                else
                {
                    this.lblBidPrice.Text = (hospitalProcureCatalog.ProcurePrice.Value == 0) ? "NA" : HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.ProcurePrice);
                    hc2012.Visible = true;
                    hc2014.Visible = false;
                    hc20142.Visible = false;
                }
                ProjectID = hospitalProcureCatalog.ProjectID;
                this.lblPackUnit.Text = hospitalProcureCatalog.PackUnit;
                if (hospitalProcureCatalog.Price != null)
                {
                    if (hospitalProcureCatalog.ProjectID == "0002")
                    {
                        this.txtPrice2014.Text = (hospitalProcureCatalog.Price.Value == 0) ? "NA" : HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.Price.Value);
                    }
                    else
                    {
                        this.txtPrice.Text = (hospitalProcureCatalog.Price.Value == 0) ? "NA" : HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.Price.Value);
                    }
                }
                if (hospitalProcureCatalog.ProjectID == "0002")
                {
                    ViewState["Price"] = this.txtPrice2014.Text.Trim();
                }
                else
                {
                    ViewState["Price"] = this.txtPrice.Text.Trim();
                }
                ViewState["ProjectID"] = hospitalProcureCatalog.ProjectID;
                this.txtReson.Text = hospitalProcureCatalog.PriceReson;  //设置采购价的原因 add by ysm 20130130
            }
        }
        public void Bind()
        {
            string where = "";
            where += " and hospitalid = '" + CurrentAccount.GetUser().UserID + "' and procurecatalogid = '" + Request.QueryString["procureCatalogId"] + "'";
            int totalCount = 0;
            DataTable dt = hpcCtrl.GetHospitalPriceLog(where, AspNetPager1.CurrentPageIndex, AspNetPager1.PageSize, out totalCount);
            AspNetPager1.RecordCount = totalCount;
            gvwAreas.DataSource = dt;
            gvwAreas.DataBind();
        }
        /// <summary>
        /// 转换布尔值为checked
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        protected string GetChecked(object obj)
        {
            if (Convert.ToString(obj) == true.ToString())
            {
                return "checked";
            }
            return "";
        }

        /// <summary>
        /// 更新采购价
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string strPrice = string.Empty;
                if (ViewState["ProjectID"].ToString() == "0002")
                {
                    if (string.IsNullOrEmpty(txtPrice2014.Text.Trim()))
                    {
                        HZ.Web.WebUtil.Alert("请填写实际采购价！", this);
                        return;
                    }
                    strPrice = txtPrice2014.Text.Trim();
                }
                else
                {
                    if (string.IsNullOrEmpty(txtPrice.Text.Trim()))
                    {
                        HZ.Web.WebUtil.Alert("请填写采购价！", this);
                        return;
                    }
                    strPrice = txtPrice.Text.Trim();
                }
                string price = ViewState["Price"].ToString();
                if (strPrice == price)
                {
                    HZ.Web.WebUtil.Alert("采购价与上次设置的采购限价相同，不要重新保存！", this);
                    return;
                }

                if (string.IsNullOrEmpty(txtReson.Text.Trim()))
                {
                    HZ.Web.WebUtil.Alert("请填写设置采购价原因、依据", this);
                    return;
                }

                if (!HZ.Common.MyValidate.IsMoney(strPrice))
                {
                    HZ.Web.WebUtil.Alert("价格格式不对！", this);
                    txtPrice.Focus();
                    return;
                }
                if (Convert.ToDecimal(strPrice) == 0)
                {
                    HZ.Web.WebUtil.Alert("价格不可用为0！", this);
                    txtPrice.Focus();
                    return;
                }

                //获取该条医疗机构产品目录的信息
                string procureCatalogId = Request.QueryString["procureCatalogId"];
                string hospitalId = CurrentAccount.GetUser().Org.OrgID;
                int tmpCount;
                HZ.DrugTrade.Model.View.HospitalProcureCatalog hospitalProcureCatalog = hpcCtrl.GetHospitalProcureCatalog(
                    new HZ.DrugTrade.Model.Query.HospitalProcureCatalog() { ProcureCatalogID = procureCatalogId, HospitalID = hospitalId }, 1, 0, out tmpCount)[0];

                if (ViewState["ProjectID"].ToString() == "0002")
                {
                    if (Convert.ToDecimal(strPrice) > hospitalProcureCatalog.ProcurePrice)
                    {
                        HZ.Web.WebUtil.Alert("采购价不能高于自主报价" + HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.ProcurePrice.Value) + "！", this);
                        txtPrice2014.Focus();
                        return;
                    }
                }
                else
                {
                    if (Convert.ToDecimal(strPrice) > hospitalProcureCatalog.ProcurePrice)
                    {
                        HZ.Web.WebUtil.Alert("采购价不能高于采购限价" + HZ.DrugTrade.Web.Function.FormPrice(hospitalProcureCatalog.ProjectID, hospitalProcureCatalog.ProcurePrice.Value) + "！", this);
                        txtPrice.Focus();
                        return;
                    }
                }

                Model.HospitalProcureCatalog model = new HospitalProcureCatalog();
                model.HospitalID = CurrentAccount.GetUser().Org.OrgID;
                model.ProcureCatalogID = Request.QueryString["procureCatalogId"];
                model.Price = Convert.ToDecimal(strPrice);
                model.PriceReson = HZ.Fun2.CheckString(txtReson.Text.Trim()); //设置采购价的原因
                model.PriceSetTime = System.DateTime.Now;   //设置采购价的时间
                model.PriceSetUserID = CurrentAccount.GetUser().UserID;  //设置采购价的用户名
                model.PriceSetUserName = CurrentAccount.GetUser().UserName; //设置采购价的用户名称

                int result = hpcCtrl.UpdateHospitalProcureCatalogCompanyPS(model);
                if (result == 1)
                {
                    string sql = string.Format(@"insert into tb_hospitalpricelog select * from tb_hospitalprocurecatalog where ProcureCatalogID='{0}' and hospitalid = '{1}'", Request.QueryString["procureCatalogId"], CurrentAccount.GetUser().UserID);
                    HZ.Data.DbHelperFactory.Create().ExecuteNonQuery(sql);
                    HZ.DrugTrade.BLL.BLL_Log.Instance.AddKeyOperationLog(new HZ.DrugTrade.Model.KeyOperationLog() { OperateMessage = string.Format("医疗机构设置采购价,产品编号【{0}】,采购价:【{1}】,原因：【{2}】，用户名称：【{3}】", model.ProcureCatalogID, model.Price, model.PriceReson, model.PriceSetUserName) });
                    PageInfo("设置成功！", "PurchasePriceUpdate.aspx?procureCatalogId=" + procureCatalogId);
                    BindAllCompanyList();
                }
                else
                {
                    PageError("设置出错！请联系管理员", this.ReturnUrl);
                }
            }
        }

        protected void AspNetPager1_OnPageChanged(object sender, EventArgs e)
        {
            Bind();
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            string where = "";
            where += " and hospitalid = '" + CurrentAccount.GetUser().UserID + "' and procurecatalogid = '" + Request.QueryString["procureCatalogId"] + "'";
            int totalCount = 0;
            DataTable dt = hpcCtrl.GetHospitalPriceLog(where, 1, 0, out totalCount);
            HZ.Excel.ExcelHelper.ExportDataForWeb(dt, gvwAreas);
        }

        protected void gvwAreas_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                if (ViewState["ProjectID"].ToString() == "0002")
                {
                    e.Row.Cells[8].Text = "自主报价";
                }
            }
        }
        /// <summary>
        /// 加载修改审核记录
        /// </summary>
        private void BindOperationRecords()
        {
            DataTable dt = HZ.Data.DbHelperFactory.Create().ExecuteTable(string.Format("select 最低历史价出处 from 参考价 where GoodsId='{0}'", GoodsId));
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    strPriceProvenance += item[0] + "<br/>";
                }
            }

        }
    }
}
